/**********************************************************************
 *                                                                    *
 * tgt - Tiny Graphics Toolbox                                        *
 *                                                                    *
 * Copyright (C) 2006-2008 Visualization and Computer Graphics Group, *
 * Department of Computer Science, University of Muenster, Germany.   *
 * <http://viscg.uni-muenster.de>                                     *
 *                                                                    *
 * This file is part of the tgt library. This library is free         *
 * software; you can redistribute it and/or modify it under the terms *
 * of the GNU Lesser General Public License version 2.1 as published  *
 * by the Free Software Foundation.                                   *
 *                                                                    *
 * This library is distributed in the hope that it will be useful,    *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of     *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the       *
 * GNU Lesser General Public License for more details.                *
 *                                                                    *
 * You should have received a copy of the GNU Lesser General Public   *
 * License in the file "LICENSE.txt" along with this library.         *
 * If not, see <http://www.gnu.org/licenses/>.                        *
 *                                                                    *
 **********************************************************************/

#include "tgt/navigation/topviewnavigation.h"
#include "tgt/matrix.h"

#include <typeinfo>

namespace tgt {

TopviewNavigation::TopviewNavigation( GLCanvas* GLCanvas, Camera* camera, int button1, int button2, int button3	)
    : Navigation( GLCanvas ), canvas_( GLCanvas ), camera_( camera )
{
    moveButton_ = button1;
    zoomButton_ = button2;
    turnButton_ = button3;
    moveButtonPressed_ = false;
    zoomButtonPressed_ = false;
    turnButtonPressed_ = false;
    moveSensitivity_ = 4;
    zoomSensitivity_ = 4;
    turnSensitivity_ = 1;
    move_ = false;
    count_ = 0;

    vec3 right = camera_->getStrafe();
    vec3 ortho = vec3( camera_->getPosition()[0], 0.0f, camera_->getPosition()[2] ) - camera_->getPosition();
    float focallength = length( ortho );
    vec3 tempLook = quat::rotate( ortho, (float) 0.01f, right );
    vec3 updateLook = focallength * tempLook;

    camera_->setUpVector( vec3( 0.f, 1.f, 0.f ) );
    camera_->setFocus( camera_->getPosition() + updateLook );
}


TopviewNavigation::~TopviewNavigation() {}


void TopviewNavigation::onEvent( Event* event ) {
    if ( typeid( *event ) == typeid( MouseEvent ) ) {
        MouseEvent* e = ( MouseEvent* ) event;
        if ( e->action() == MouseEvent::PRESSED ) {
            currentX_ = e->x();
            currentY_ = e->y();
            from_ = camera_->getPosition();
            to_ = camera_->getFocus();
            up_ = camera_->getUpVector();
            y_up_ = Vector( 0.0, 1.0, 0.0);
            dir_ = normalize(to_ - from_);
            right_ = normalize( cross(up_, dir_) );
            gogo_ =  normalize( cross(y_up_, right_) );
            xValue_ = 0;
            yValue_ = 0;

            // if move button pressed
            if ( e->button() == moveButton_ ){
                moveButtonPressed_ = true;
                glGetIntegerv( GL_VIEWPORT, viewport_ );
                glGetDoublev( GL_MODELVIEW_MATRIX, mvmatrix_ );
                glGetDoublev( GL_PROJECTION_MATRIX, projmatrix_ );

                getProjectedCursorCoordinates(e->x(),e->y(),viewport_,mvmatrix_,projmatrix_,true);
            }

            // if zoom button pressed
            if ( e->button() == zoomButton_ ){
                zoomButtonPressed_ = true;
            }

            // if turn button pressed
            if ( e->button() == turnButton_ ){
                turnButtonPressed_ = true;
            }

            if ( e->button() == MouseEvent::MOUSE_WHEEL_UP
                    || e->button()==MouseEvent::MOUSE_WHEEL_DOWN ){

                dir_ = normalize( camera_->getFocus() - camera_->getPosition() );

                switch ( e->button() ) {
                    case MouseEvent::MOUSE_WHEEL_UP:
                        camera_->setPosition( from_ + (float) zoomSensitivity_ * 2.f * dir_ );
                        camera_->setFocus( to_ + (float) zoomSensitivity_ * 2.f * dir_ );
                        break;
                    case MouseEvent::MOUSE_WHEEL_DOWN:
                        camera_->setPosition( from_ - (float) zoomSensitivity_ * 2.f * dir_ );
                        camera_->setFocus( to_ - (float) zoomSensitivity_ * 2.f * dir_ );
                        break;
                    default:
                      break;
                }
            }
            canvas_->update();

            if( e->action() == MouseEvent::RELEASED ) {
                // if moveButton released
                if ( e->button() == moveButton_ ) {
                    moveButtonPressed_ = false;
                }
                // if zoomButton released
                if ( e->button() == zoomButton_ ) {
                    zoomButtonPressed_ = false;
                }
                // if turnButton released
                if ( e->button() == turnButton_ ) {
                    turnButtonPressed_ = false;
                }
            }

            if( e->action() == MouseEvent::MOTION ) {
                if ( ( e->x() > 0 ) && ( e->y() > 0 ) ) {
                    float h = camera_->getPosition().y * 0.025f;

                    float dx = (float) ( e->x() - currentX_ );
                    float dy = (float) ( e->y() - currentY_ );

                    if ( moveButtonPressed_ && !zoomButtonPressed_ && !turnButtonPressed_ ) {
                        dx *= (float)moveSensitivity_ * h * 0.1f;
                        dy *= (float)moveSensitivity_ * h * 0.1f;
                        xValue_ += dx;
                        yValue_ -= dy;
                    }
                    if ( turnButtonPressed_ && !moveButtonPressed_ && !zoomButtonPressed_ ) {
                        dx *= (float)turnSensitivity_ * 0.1f;
                        dy *= (float)turnSensitivity_ * 0.1f;
                        xValue_-= dx;
                        yValue_-= dy;
                    }
                    if ( !turnButtonPressed_ && !moveButtonPressed_ && zoomButtonPressed_ ) {
                        dx *= (float)turnSensitivity_ * 0.1f;
                        dy *= (float)turnSensitivity_ * 0.1f;
                        xValue_+= dx;
                        yValue_-= dy;
                    }

                    // mouse movement and button pressed
                    if( moveButtonPressed_ && !zoomButtonPressed_ && !turnButtonPressed_ ) {
                        GLdouble objx, objy, objz;
                        GLdouble winx, winy, winz;

                        winx = (double) e->x();
                        winy = (double) viewport_[3] - (double) e->y();

                        glReadPixels( e->x(), (int) winy, 1, 1, GL_DEPTH_COMPONENT, GL_DOUBLE, &winz );
                        // FIXME: should we really use GLU in tgt??
                        gluUnProject( winx, winy, winz, mvmatrix_, projmatrix_, viewport_, &objx, &objy, &objz );

                        vec3 trans = vec3( (float)objx, (float)objy, (float)objz ) - moveStart_;

                        camera_->setPosition( from_ - vec3( trans[0], 0.f, trans[2] ) );
                        camera_->setFocus( to_ - vec3( trans[0], 0.f, trans[2] ) );

                        canvas_->update();
                    }

                    // mousemovement and move and turn = zoom pressed
                    if( !moveButtonPressed_ && !zoomButtonPressed_ && turnButtonPressed_ ){
                        dir_ = normalize( camera_->getFocus()-camera_->getPosition() );

                        vec3 look = quat::rotate( ( to_ - from_ ), 0.01f * (float) xValue_, y_up_);
                        camera_->setFocus( from_ + look + (float) yValue_ * dir_ );

                        canvas_->update();
                    }

                    // mousemovement and mous button pressed
                    if( !moveButtonPressed_ && zoomButtonPressed_ && !turnButtonPressed_ ){
                        dir_ = normalize( camera_->getFocus() - camera_->getPosition() );

                        camera_->setPosition( from_ + (float) yValue_ * dir_ );
                        canvas_->update();

                    }
                    currentX_ = e->x();
                    currentY_ = e->y();
                }
            }
        }
    }
}

vec3 TopviewNavigation::getProjectedCursorCoordinates(int x, int y, GLint viewport[4], GLdouble mvmatrix[16], GLdouble projmatrix[16], bool ground) {
    GLdouble objx, objy, objz;
    GLdouble winx, winy;
    GLdouble z;
    winx = (double) x;
    winy = (double) viewport[3] - (double) y;

    if (!ground) {
        glReadBuffer(GL_BACK);
        glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_DOUBLE, &z);
    }
    // FIXME: should we really use GLU in tgt??
    gluUnProject(winx,winy,z,mvmatrix,projmatrix,viewport,&objx,&objy,&objz);

    return vec3((float)objx, (float)objy, (float)objz);
}

}// namespace tgt
